<template>
	<!-- 订单列表 -->
	<view class="order-pages">
		<fixed>
			<tab @change="handerTabChange" :list="tabList" :activeIndex="activeIndex*1" :activeColor="primaryColor"
				:width="100/tabList.length + '%'" height="100rpx"></tab>
			<view class="b-1px-b"></view>
		</fixed>
		
		<view @tap.stop="goDetail(index,'detail')" class="item-child mt-md ml-md mr-md pd-lg fill-base radius-16"
			v-for="(item,index) in list.data" :key="index">
			<view @tap.stop="goShop(index)" class="flex-between pb-lg b-1px-b">
				<view class="f-paragraph c-title max-500 ellipsis">订单号：{{item.order_code}}</view>
				<!-- // pay_type 1待支付，2待服务，3技师接单，4技师出发，5技师到达，6服务中，7服务完成 -->
				<view class="f-caption text-bold"
					:style="{color:item.pay_type==1?primaryColor: [2,3,4,5,6].includes(item.pay_type)?subColor: item.pay_type == 7 ? '#11C95E' : '#333'}">
					{{statusType[item.pay_type]}}
				</view>
			</view>
			<view class="flex-center mt-lg" v-for="(aitem,aindex) in item.order_goods" :key="aindex">
				<image mode="aspectFill" class="cover radius-16" :src="aitem.goods_cover"></image>
				<view class="flex-1 ml-md">
					<view class="flex-between">
						<view class="f-title c-title text-bold max-400 ellipsis">
							{{aitem.goods_name}}
						</view>
						<view class="f-desc c-desc">x{{aitem.num}}</view>
					</view>
					<view class="flex-center" style="margin-bottom: 5rpx;">
						<view class="flex-1 flex-y-center f-caption c-caption mt-md"  v-if="item.order_type ==2"> 服务<view class="ml-md" v-if="item.coach_info">
								{{item.coach_info.coach_name}}
							</view>
						</view>
						<view class="f-caption c-warning" v-if="aitem.refund_num>0">已退x{{aitem.refund_num}}
						</view>
					</view>
					<view class="flex-y-center f-caption c-caption" v-if="item.order_type ==2">预约时间<view class="ml-md">{{item.start_time}}</view>
					</view>
					<view class="flex-y-center f-caption c-caption" v-else>支付时间<view class="ml-md">{{item.pay_time}}</view>
					</view>
				</view>
			</view>
			<view class="flex-between pt-lg">
				<view class="flex-y-center f-desc c-title">总计：
					<view class="f-paragraph c-title text-bold">¥{{item.pay_price}}</view>
				</view>
				<view class="flex-warp">
					<!-- // pay_type 1待支付，2待服务，3技师接单，4技师出发，5技师到达，6服务中，7服务完成，8待评价 -->
					<!-- 待支付 -->
					<block v-if="item.pay_type == 1">
						<button @tap.stop="toCancel(index)" class="clear-btn order">取消订单</button>
						<button @tap.stop="toPay(index)" class="clear-btn order"
							:style="{color:'#fff',background:primaryColor,borderColor:primaryColor}">去支付</button>
					</block>
					<!-- 支付超时 -->
					<block v-if="item.pay_type == -1">
						<button @tap.stop="toCancel(index)" class="clear-btn order">删除</button>
					</block>
					<!-- 待服务 -->
					<button class="clear-btn order" @tap.stop="goDetail(index,'refund')" v-if="item.can_refund > 0">申请售后</button>
					<button @tap.stop="todelivery(item.id)" class="clear-btn order"
						v-if="item.can_refund > 0">确认收货</button>
					<!-- 已完成 -->
					<block v-if="item.pay_type == 7">
						<button @tap.stop="goDetail(index,'evaluate')" class="clear-btn order"
							v-if="!item.is_comment">去评价</button>
						<button @tap.stop="toAgain(item.order_goods[0].goods_id)" class="clear-btn order"
							:style="{color:'#fff',background:primaryColor,borderColor:primaryColor}">再来一单</button>
					</block>
				</view>
			</view>
		</view>
		
		<load-more :noMore="list.current_page>=list.last_page&&list.data.length>0" :loading="loading" v-if="loading">
		</load-more>
		<abnor v-if="!loading&&list.data.length<=0&&list.current_page==1"></abnor>
		
		<view class="space-footer"></view>
		
		<common-popup @confirm="confirmCancel" ref="cancel_item" type="CANCEL_ORDER" :info="popupInfo"></common-popup>
		<common-popup @confirm="confirmDel" ref="del_item" type="DELETE_ORDER" :info="popupInfo"></common-popup>
		
		<view :style="{height: `${configInfo.tabbarHeight}px`}"></view>
		<tabbar :cur="3"></tabbar>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	
	import tabbar from "@/components/tabbar.vue"
	export default {
		components: {
			tabbar
		},
		data() {
			return {
				options: {},
				pageActive: false,
				activeIndex: 0,
				tabList: [{
					title: '全部',
					id: 0
				}, {
					title: '待支付',
					id: 1,
					// number: 10
				}, {
					title: '待发货',
					id: 5
				}, {
					title: '待收货',
					id: 3
				}, {
					title: '已完成',
					id: 7
				}, {
					title: '评价',
					id: 5
				}, {
					title: '退款',
					id: 8
				}],
				statusType: {
					'-1': '已取消',
					1: '待支付',
					2: '待发货',
					3: '商家已发货',
					4: '待签收',
					5: '已签收',
					6: '已评价',
					7: '已完成',
					8: '已退款',
				},
				param: {
					page: 1,
					pay_type: 0,
				},
				list: {
					data: [],
					last_page: 1,
					current_page: 1
				},
				carList: {},
				haveOperItem: false,
				loading: true,
				popupInfo: {},
				index: -1,
				coach_refund_text: '',
				lockTap: false,
				unix_list: []
			}
		},
		computed: mapState({
			primaryColor: state => state.config.configInfo.primaryColor,
			subColor: state => state.config.configInfo.subColor,
			configInfo: state => state.config.configInfo,
			userInfo: state => state.user.userInfo,
		}),
		onBackPress(options) {
		  uni.redirectTo({
		  	url:'/pages/service'
		  })
		} ,
		onLoad(options) {
			this.options = options
			let {
				tab = 0
			} = options
			this.activeIndex = tab
			this.initIndex()
		},
		onPullDownRefresh() {
			this.initRefresh();
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			if (this.list.current_page >= this.list.last_page || this.loading) return;
			this.param.page = this.param.page + 1;
			this.loading = true;
			this.getList();
		},
		methods: {
			...mapActions(['getConfigInfo']),
			...mapMutations(['']),
			async initIndex(refresh = false) {
				this.$util.setNavigationBarColor({
					bg: this.primaryColor
				})
				if (!this.configInfo.id || refresh) {
					await this.getConfigInfo()
				}
				await this.getList(1)
			},
			initRefresh() {
				this.param.page = 1
				this.initIndex(true)
			},
			async getList(page = 0) {
				this.param.page = page
				this.loading = false
				this.$util.hideAll()
				let {
					list: oldList,
					param,
					tabList,
					activeIndex
				} = this
				param.pay_type = tabList[activeIndex].id
				let newList = await this.$api.order.orderList(param)
				if (this.param.page == 1) {
					this.list = newList
				} else {
					newList.data = oldList.data.concat(newList.data)
					this.list = newList
				}
				this.tabList[0].number = newList.agent_order_count
				this.loading = false
				this.$util.hideAll()
			},
			handerTabChange(index) {
				this.activeIndex = index;
				uni.pageScrollTo({
					scrollTop: 0
				})
				this.$util.showLoading()
				this.param.page = 1;
				this.getList(1)
			},
			// 门店
			async goShop(index) {
				let {
					id: cap_id
				} = this.list.data[index].cap_info
				await this.$api.order.selectCap({
					cap_id
				})
				this.$util.goUrl({
					url: `/pages/index?key=2`
				})
			},
			// 取消/删除订单
			async toCancel(index) {
				let {
					id,
					order_code,
					order_goods,
					pay_type,
				} = this.list.data[index]
				let {
					goods_cover: image,
				} = order_goods[0]
				this.popupInfo = {
					id,
					name: `系统单号：${order_code}`,
					image,
					index,
				}
				let refs_key = pay_type == -1 ? 'del_item' : 'cancel_item'
				this.$refs[refs_key].open()
			},
			// 确认：取消订单
			async confirmCancel() {
				let {
					id,
					index,
				} = this.popupInfo
				await this.$api.order.cancelOrder({
					id
				})
				if (this.activeIndex == 0) {
					this.list.data[index].pay_type = -1
				} else {
					this.list.data.splice(index, 1)
				}
				this.$util.showToast({
					title: `取消成功`
				})
				this.$refs.cancel_item.close()
			},
			// 确认：删除订单
			async confirmDel() {
				let {
					id,
					index,
				} = this.popupInfo
				await this.$api.order.delOrder({
					id
				})
				this.list.data.splice(index, 1)
				this.$util.showToast({
					title: `删除成功`
				})
				this.$refs.del_item.close()
			},
			// 去支付
			async toPay(index) {
				if (this.lockTap) return;
				this.lockTap = true;
				this.$util.showLoading()
				let {
					id
				} = this.list.data[index]
			
				try {
					let {
						pay_list
					} = await this.$api.order.rePayOrder({
						id
					})
					this.$util.hideAll()
					if (pay_list) {
						try {
							await this.$util.pay(pay_list)
							this.$util.showToast({
								title: `支付成功`
							})
							if (this.activeIndex == 0) {
								this.list.data[index].pay_type = 2
							} else {
								this.list.data.splice(index, 1)
							}
							this.lockTap = false;
						} catch (e) {
							this.lockTap = false;
							return
						}
					}
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			},
			todelivery(oid)
			{
				const vm = this;
				let param = {
					order_id:oid
				}
				uni.showModal({
					title: '提示',  
					    content: '你确定收到货了吗？',  
					    success: function (res) {  
					        if (res.confirm) {  
							vm.handleConfirm(oid);
					        } else if (res.cancel) {  
					            console.log('用户点击取消');  
								return
					            // 用户点击取消后的操作  
					        }  
					    } 
				})
			
			},
	async handleConfirm(oid) { 
		
	            try {  
					let param = {
						order_id:oid
					}
	                const data = await this.$api.order.todelivery(param); // 发起异步请求  
						uni.showToast({
							title:data.data,
							duration:3000,
							icon:'success'
						})
						this.activeIndex = 4
					this.getList(1)
	                console.log('获取数据成功:', data);  
	                // 在这里处理获取到的数据  
	            } catch (error) {  
	                console.error('获取数据失败:', error);  
	                // 在这里处理错误  
	            }  
	        } ,
			// 去核销
			async toHx(index) {
				let {
					id,
					qr: image
				} = this.list.data[index]
				this.popupInfo = {
					id,
					image
				}
				this.$refs.hx_item.open()
			},
			// 订单详情/申请退款/去评价
			goDetail(index, page) {
				let {
					id
				} = this.list.data[index]
				let url = `/user/pages/order/${page}?id=${id}`
				this.$util.goUrl({
					url
				})
			},
			// 再来一单
			async toAgain(gid) {
			// 	let {
			// 		id: order_id,
			// 		coach_id
			// 	} = this.list.data[index]
			
			// 	await this.$api.order.onceMoreOrder({
			// 		order_id
			// 	})
				this.$util.goUrl({
					url: `/user/pages/shop/goods-detail-pay?id=${gid}`
				})
			}
		}
	}
</script>


<style lang="scss">
</style>
